const $T = uni;

/** Toast提示 */
export const Toast = function (title = '提示', icon  = 'none') {
  return $T.showToast({ title: title, icon: icon });
};

/** 模态确认 */
export const Modal = function (data) {
  let params = {
    showCancel: false,
    content: '',
    confirmColor: '#1790FF',
    cancelColor: '#323232',
    confirmText: '是',
    cancelText: '否',
    ...data
  };
  return new Promise((resolve, reject) => {
    uni.showModal({
      // title: '提示',
      ...params,
      success: function (res) {
        if (res.confirm) {
          resolve(res);
          console.log('用户点击确定');
        } else if (res.cancel) {
          resolve(res);
          console.log('用户点击取消');
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};



/** 函数节流 */
export const Throttle = function () {
  let t = 0 ;
  return function (cd, time = 500) {
    if (t) return time > 500 && Toast('请勿频繁操作!');
    cd();
    t = setTimeout(() => (t = 0), time);
  };
};

/** 函数防抖 */
export const Debounce = function (time = 50) {
  let t = 0 ;
  return function (cd) {
    if (t) clearTimeout(t);
    t = setTimeout(() => cd(), time);
  };
};

/** 显示加载状态 */
export const Loading = function (title = '加载中~', mask = false, duration = 6e4) {
  // console.log({ title, mask, duration })
  if (duration == 0) duration = 9e8;
  const success = () => setTimeout(() => $T.hideLoading(), duration);
  $T.showLoading({
    title,
    mask,
    success
  });
  return {
    close: $T.hideLoading,
    Loading
  };
};

/** 设置导航栏加载状态 */
export const BarLoading = function (duration = 6e4) {
  const success = () => setTimeout(() => $T.hideNavigationBarLoading(), duration);
  // @ts-ignore
  $T.showNavigationBarLoading({ success });
  return {
    close: $T.hideNavigationBarLoading,
    ...$T
  };
};

/** 设置剪辑版 */
// export const setClipboard = function (data = '') {
//   return new Promise((success, fail) =>
//     $T.setClipboardData({
//       data,
//       success,
//       fail
//     })
//   );
// };

export const getCascadeData = function (maxLevel = 3) {
  const arr = [];
  function setChildData(dataContainer, pId = '', level = 0) {
    // console.log('setChildData');
    for (let i = 0; i < 10; i++) {
      const id = pId ? `${pId}-${i}` : `${i}`;
      const itemData = {
        name: `${id}`,
        id: id,
        children: []
      };
      if (level + 1 < maxLevel) {
        setChildData(itemData.children, id, level + 1);
      }
      dataContainer.push(itemData);
    }
  }
  setChildData(arr);
  // console.log('arr', arr);
  return arr;
};
